<template>
  <form class="validate-from-container">
    <slot name="default"></slot>
    <div class="submit-area" @click.prevent="submitForm">
      <slot name="submit">
        <button type="submit" class="btn btn-primary">提交</button>
      </slot>
    </div>
  </form>
</template>

<script lang='ts'>
import { defineComponent, onUnmounted, provide } from 'vue'
import mitt from 'mitt'

type ValidateFunc = () => boolean
type ClearFunc = () => void
type Events = {
  'form-item-created': any
}
interface CallbackProps {
  validator: ValidateFunc
  clearInput: ClearFunc
  formName: string
}

export const emitter = mitt<Events>()
export default defineComponent({
  name: 'ValidateForm',
  emits: ['form-submit'],
  props: {
    // 请提供不同的 formName 当使用多个表单在同一个页面中的时候
    name: {
      type: String,
      default: 'default'
    }
  },
  setup(props, context) {
    provide('formName', props.name)
    let funcArr: ValidateFunc[] = []
    let clearArr: ClearFunc[] = []

    const submitForm = () => {
      // 循环执行数组 得到最后的验证结果
      const result = funcArr.map((func) => func()).every((result) => result)
      context.emit('form-submit', result)
    }
    // 将监听得到的验证函数都存到一个数组中
    const callback = (obj?: CallbackProps) => {
      if (obj && obj.formName === props.name) {
        funcArr.push(obj.validator)
        clearArr.push(obj.clearInput)
      }
    }
    const clearInputs = () => {
      clearArr.forEach((clear) => clear())
    }
    // 添加监听
    emitter.on('form-item-created', callback)
    onUnmounted(() => {
      // 删除监听
      emitter.off('form-item-created', callback)
      funcArr = []
      clearArr = []
    })
    return {
      submitForm,
      clearInputs
    }
  }
})
</script>

<style>
</style>
